import sys
import ctypes
from PySide6.QtWidgets import * # type: ignore
from PySide6.QtCore import * # type: ignore
from PySide6.QtGui import * # type: ignore

def isAdminMode() -> bool:
    '''Check if running with administrator privileges'''
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception:
        return False
    
def restartAsAdmin() -> None:
    '''Restart application with admin rights'''
    ctypes.windll.shell32.ShellExecuteW(
        None,
        'runas',
        sys.executable,
        ' '.join(sys.argv),
        None,
        1
    )

def getUIAccess(window: QWidget) -> None:
    '''Grant UI Access pinning permission to the window for better top-most effect'''
    # Ensure admin rights for UI Access
    if not isAdminMode() and '--island-no-admin' not in sys.argv:
        restartAsAdmin()

    # Get window handle and set display affinity for pinning
    hwnd = int(window.winId())
    user32 = ctypes.windll.user32
    user32.SetWindowDisplayAffinity(hwnd, 1)  # WDA_MONITOR - enables pinning